<?php

namespace App\Admin\Controllers;

use App\Models\SaleUser;
use App\Models\SaleRole;
use App\Models\ShopUser;
use App\Models\Order;
use App\Models\OrderCount;
use App\Models\VOrder;
use App\Models\OrderDetail;
use App\Models\ViewOrder;
use App\Models\OrderAddress;
use App\Models\SaleProfitOrder;
use App\Models\InvoiceImg;
use App\Models\CEOApply;

use App\Http\Controllers\Controller;
use Illuminate\Routing\Router;
use Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

include_once "common.php";

class UserController extends Controller
{
    function test(){
        echo 'ss';
    }
    // CEO申请
    function ceo_apply(){
      $input = Request::all();
      
      $db = new CEOApply();
 
      $db->name = $input['name'];
      $db->gender = $input['gender'];
      $db->age = $input['age'];
      $db->city = $input['city'];
      $db->job = $input['job'];
      $db->work_mode = $input['work_mode'];
      $db->mobile = $input['mobile'];
      $db->resource = $input['resource'];
      $db->exp = $input['exp'];
      $db->save();
      
      if(!$db){ 
        return json_res(1,'申请失败');
      }
      return json_res(0,'ok');
    }
    function post1($url, $data){//file_get_content
        $postdata = http_build_query(
            $data
        );
        $opts = array('http' =>
                      array(
                          'method'  => 'POST',
                          'header'  => 'Content-type: application/x-www-form-urlencoded',
                          'content' => $postdata
                      )
        );
        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
        return json_decode($result,true);
    }
    // 发送验证码
    function send_code(){
      $mobile = Request::input('mobile');
      $url = 'https://www.machineeye.cn/api/sendPhoneCode';
      if(!SaleUser::where('mobile', '=', $mobile)->exists()){
        return json_res(1,'该用户不存在');
      };
      
      
      $data = array('mobile'=>$mobile,'code_type'=>1);
      $res = $this->post1($url,$data);
      
      if($res['statusCode'] !== 0){
        return json_res(1,$res['msg']);
      }
      return json_res(0,'ok');

    }
    // 验证验证码，修改密码
    function change_pwd(){
      $mobile = Request::input('mobile');
      $code = Request::input('code');
      $pwd = Request::input('pwd');
      $url = 'https://www.machineeye.cn/api/checkedPhoneCode';
      $data = array('mobile'=>$mobile,'code_type'=>1,'code'=>$code);
      
      $res = $this->post1($url,$data);
      
      if($res['statusCode'] !== 0){
        return json_res(1,$res['msg']);
      }
      
      $db = SaleUser::where('mobile',$mobile)->update(['password'=>$pwd]);
      return json_res(0,'ok');
    }
    // CEO申请 new
    function ceo_apply_new(){
      $input = Request::all();
      
      
      $db1 = CEOApply::where('ceo_mobile','=',$input['ceo_form']['mobile'])->where('status',2)->exists();  
      if($db1){
        return json_res(1,'CEO手机号已注册');
      }
      $db1 = CEOApply::where('ceo_mobile','=',$input['ceo_form']['mobile'])->where('status',1)->exists();  
      if($db1){
        return json_res(1,'该CEO账号提审中');
      }
      $db2 =  CEOApply::where('store_mobile','=',$input['store_form']['mobile'])->where('status',2)->exists();
       if($db2){
        return json_res(1,'药店手机号已注册');
      }
      $db2 =  CEOApply::where('store_mobile','=',$input['store_form']['mobile'])->where('status',1)->exists();
       if($db2){
        return json_res(1,'该药店账号提审中');
      }
      $db = new CEOApply();
      
      $db->ceo_mobile = $input['ceo_form']['mobile'];
      $db->store_mobile = $input['store_form']['mobile'];
      $db->name =  $input['ceo_form']['name'];
      $db->apply_json = json_encode($input);

      $db->save();
      
      return json_res(0,'申请成功',$db->id);
      
    }
    //创建CEO账号
    function create_ceo($ceo_form){
    
      $db = new SaleUser();
      $db->role_id = '4';
      $db->mobile = $ceo_form['mobile'];
      $db->password = '111111';
      $db->name = $ceo_form['name'];
      $db->province = $ceo_form['areaList']['province'];
      $db->city = $ceo_form['areaList']['city'];
      $db->area = $ceo_form['areaList']['area'];
      $db->save();
      
      return $db->id;
    }
    //创建药店账号
    function create_store($store_form,$ceo_id){
      $db = new SaleUser();
      $db->role_id = '3';
      $db->mobile = $store_form['mobile'];
      $db->password = '111111';
      $db->name = $store_form['linkMan'];
      $db->store_linkman = $store_form['linkMan'];
      $db->province = $store_form['areaList']['province'];
      $db->city = $store_form['areaList']['city'];
      $db->area = $store_form['areaList']['area'];
      $db->address = $store_form['address'];
      $db->ceo_id = $ceo_id;
      //$db->store_id = $db->id;
      $db->save();
      
      $store_id = $db->id;
      
      $db2 = SaleUser::find($ceo_id);
      $db2->store_id = $store_id;
      $db2->ceo_id = $ceo_id;
      $db2->save();
      
      $db3 = SaleUser::find($store_id);
      $db3->store_id = $store_id;
      $db3->save();
      return $db->id;
      
    }

    // 获得申请列表
    function get_ceo_apply_list(){
      $db = CEOApply::where('status','1')->orderBy('created_at','desc');
      $total = $db->count();
      $res = $db->get()->toArray();
      return json_res(0,'ok',['total'=>$total,'list'=>$res]);
    }
    // 获得单个申请
    function get_ceo_apply_by_id(){
      $id = Request::input('id');
      $res = CEOApply::find($id)->toArray();
      return json_res(0,'ok',$res);
    }
    // 改变申请状态
    function set_ceo_apply(){
      $id = Request::input('id');
      $status = Request::input('status');
      
      if($status == '3'){
        $db = CEOApply::find($id);
        $db->status = $status;
        $db->save();
        if(!$db){
          return json_res(1,'失败');
        }
        return json_res(0,'ok');
      }
      $db = CEOApply::find($id);
      $apply_json = json_decode($db->apply_json,true);
      
      $ceo_id = $this->create_ceo($apply_json['ceo_form']);
      $store_id = $this->create_store($apply_json['store_form'],$ceo_id);
      
      
      if($ceo_id && $store_id){
        $db->status = $status;
        $db->save();
        if(!$db){
          return json_res(1,'失败');
        }
          return json_res(0,'ok');
      }
      
    }
    // 获得历史申请
    function get_history_ceo_apply(){
      $status = Request::input('status');
      if($status == NULL){
        $db = CEOApply::whereIn('status',['2','3']);
        return json_res(0,'ok',$db->orderBy('created_at','desc')->get()->toArray());
      }
      $db = CEOApply::where('status',$status);
      return json_res(0,'ok',$db->orderBy('created_at','desc')->get()->toArray());
    }
    function set_bankcard(){
      $bankcard = Request::input('bankcard');
      $bankcard_man = Request::input('bankcard_man');
      $myinfo = $this->get_user_data_by_cookie();
      if(!$myinfo){
        return json_res(1,'验证失败');
      }
      $id = $myinfo['id'];
      
      $db = SaleUser::find($id);
      if(!$db){
        return json_res(1,'用户不存在');
      }
      $db->bankcard = $bankcard;
      $db->bankcard_man = $bankcard_man;
      $db->save();
      return json_res(0,'ok');
    }
    function get_bankcard(){
      $myinfo = $this->get_user_data_by_cookie();
      if(!$myinfo){
        return json_res(1,'验证失败');
      }
      $id = $myinfo['id'];
      
      $db = SaleUser::find($id);
      if(!$db){
        return json_res(1,'用户不存在');
      }
      $bankcard = $db->bankcard;
      $bankcard_man = $db->bankcard_man;
      
      return json_res(0,'ok',['bankcard'=>$bankcard,'bankcard_man'=>$bankcard_man]);
    }
    // 获得待审核统计信息
    function get_all_profit_info(){
      $db = SaleProfitOrder::where('status',2);
      $profit_count = $db->count();
      $price = $db->sum('price');
      $have_invoice_count = $db->where('have_invoice',1)->count();
      return json_res(0,'ok',['profit_count'=>$profit_count,'price'=>$price,'have_invoice_count'=>$have_invoice_count]);
    }
    // 获得单个提现订单
    function get_profit_order_by_id(){
      $id = Request::input('id');
      
      $db = SaleProfitOrder::find($id);
      $order = $db->toArray();  
      if($order['have_invoice']){
        $order['img_list'] = InvoiceImg::where('profit_order_id',$order['id'])->get('img_path')->toArray();           
      }
      return json_res(0,'ok',$order);
    }
    // 获得待审核提成订单(管理人员) 含搜索
    function search_profit_order_for_manage(){
      $input = Request::all();
      $db = SaleProfitOrder::where('user_id',$input['id'])->where('profit_type',$input['profit_type'])->orderBy('created_at','desc');
      if($input['status']){
        $db->where('status',$input['status']);
      }
      $order = $db->get()->toArray();  
      foreach($order as $k=>$v){
        if($v['have_invoice']){
          $order[$k]['img_list'] = InvoiceImg::where('profit_order_id',$v['id'])->get('img_path')->toArray();           
        }
      }
      
      return json_res(0,'ok',$order);  
    }
    // 获得待审核提成订单(会计) 含搜索
    function search_profit_order_for_kuaiji(){
      $input = Request::all();
      
      $db = SaleProfitOrder::orderBy('created_at','desc');
      if($input['status']){
        $db->where('status',$input['status']);
      }
      $order = $db->get()->toArray();  
      foreach($order as $k=>$v){
        if($v['have_invoice']){
          $order[$k]['img_list'] = InvoiceImg::where('profit_order_id',$v['id'])->get('img_path')->toArray();           
        }
      }
      
      return json_res(0,'ok',$order);  
    }
    // 改变审核订单状态 status:1 成功;status:3 驳回;
    function change_profit_status(){
      $id = Request::input('id');
      $msg = Request::input('msg');
      $status = Request::input('status');
      
      $db = SaleProfitOrder::find($id);
      if(!$db){
        return json_res(1,'订单错误');
      }
      $db->status = $status;
      $db->msg = $msg;
      $db->save();
      return json_res(0,'ok');
    }
    // 获得待审核提成订单(会计) 含搜索
    function search_profit_order(){
      $input = Request::all();
      
      $db = SaleProfitOrder::where('status',2)->orderBy('created_at','desc');
      foreach($input as $k=>$v){
            if($v){
                $db->where($k,$v);
            }
        }
      $order = $db->get()->toArray();  
      foreach($order as $k=>$v){
        if($v['have_invoice']){
          $order[$k]['img_list'] = InvoiceImg::where('profit_order_id',$v['id'])->get('img_path')->toArray();           
        }
      }
      
      return json_res(0,'ok',$order);  
    }
    // 创建提成订单
    function create_profit_order(){
      $input = json_decode(Request::getContent(), true);
      
      $price = $input['price'];
      $image_list = $input['image_list'];
      $id = $input['id'];
      $profit_type = $input['profit_type'];
      // $have_invoice 1:有发票 0:无发票
      $have_invoice = $input['have_invoice'];
      $profit_order_id = Null;
      //获取提现人相关信息     
      $user_info = SaleUser::find($id);
      $name = $user_info->name;
      $mobile = $user_info->mobile;
      $role_id = $user_info->role_id;
      $bankcard = $user_info->bankcard;
      $bankcard_man = $user_info->bankcard_man;
      $role_tag = SaleRole::where('role_id',$role_id)->first()->des;
      // 创建提现订单
      $db = new SaleProfitOrder();
      $db->user_id = $id;
      $db->price = $price;
      $db->role_tag = $role_tag;
      $db->name = $name;
      $db->mobile= $mobile;
      $db->have_invoice = $have_invoice;
      $db->bankcard = $bankcard;
      $db->bankcard_man = $bankcard_man;
      $db->profit_type = $profit_type;
      $db->save();
      $profit_order_id = $db->id;
      //return json_res(0,'ok',$db);
      // your base64 encoded
      if($have_invoice){
         foreach($image_list as $v){
        //$image = str_replace('data:image/png;base64,', '', $v);
        //$image = str_replace(' ', '+', $image);
        
        preg_match('/^(data:\s*image\/(\w+);base64,)/',$v,$res);
        $type = $res[2];
        $base64_img=base64_decode(str_replace($res[1],'', $v));
        $imagePath= 'images/'.Str::random(15).'.'.$type;
        Storage::disk('public')->put($imagePath, $base64_img);
        //修改
        
        //$baseUrl = "https://www.bjbayes.com/hongfei/profit/storage/app/public/";
        $baseUrl = explode("profit",Request::url())[0].'profit'.'/storage/app/public/';
        $db = new InvoiceImg();
        $db->profit_order_id = $profit_order_id;
        $db->img_path = $baseUrl.$imagePath;
        $db->save();
        }
      }           
      return json_res(0,'ok',$db);
    }
    // 获得物流提成信息
    function get_profit_info_for_wuliu(){
      $id = Request::input('id');
      
      $all_profit = SaleUser::find($id)->all_profit;
      $db = SaleProfitOrder::where('user_id',$id);
      
      $no_case_out = $db->whereIn('status',[1,2])->sum('price');
      $case_out = $all_profit - $no_case_out;
      $res = array('all_profit'=>$all_profit,'no_case_out'=>$no_case_out,'case_out'=>$case_out);
      
      return json_res(0,'ok',$res);
    }
    // 获得提成信息 
    function get_profit_info(){
      $id = Request::input('id');
      $profit_type = Request::input('profit_type');
      if($profit_type == 1){
        $all_profit = SaleUser::find($id)->all_profit;
      }
      if($profit_type == 2){
        $all_profit = SaleUser::find($id)->all_wuliu_profit;
      }
      
      $db = SaleProfitOrder::where('user_id',$id)->where('profit_type',$profit_type);
      
      $no_case_out = $db->whereIn('status',[1,2])->sum('price');
      $case_out = $all_profit - $no_case_out;
      $res = array('all_profit'=>round($all_profit,2),'no_case_out'=>round($no_case_out,2),'case_out'=>round($case_out,2));
      
      return json_res(0,'ok',$res);
    }
    
    
    function upload_express_info(){
        $order_id= Request::input('order_id');
        $express_name= Request::input('express_name');
        $express_number= Request::input('express_number');
        $db = Order::find($order_id);
        $db->status = 3;
        $db->express_name = $express_name;
        $db->express_number = $express_number;
        $db->delivery_time = time();
        $db->save();
        return json_res(0,'ok');
    }

    function get_shipments_list(){
        $id = Request::input('id');
        $res=array();
        $db=VOrder::where('status',2)->where('store_id',$id);
        
        if($db->count() == 0){
          return json_res(0,'ok',[]);
        }
        $rcs = $db->get()->toArray();

        foreach ($rcs as $r){
            if (!isset($res['items'][$r['id']])){
                $name=ShopUser::find($r['user_id'])->username;
                $db=OrderAddress::where('order_id',$r['id'])->first();
                $res['items'][$r['id']]['address']=$db->province_name.$db->city_name.$db->county_name.$db->address;
                $res['items'][$r['id']]['tel']=$db->tel;
                $res['items'][$r['id']]['username']=$name;
                $res['items'][$r['id']]['order_id']=$r['id'];
                $res['items'][$r['id']]['goods_recieve_type']=$r['goods_recieve_type'];
            }
            $res['items'][$r['id']]['details'][]=array('goods_name'=>$r['title'], 'count'=>$r['buy_number_count']);
        }
        $items=array();
        foreach($res['items'] as $r){
            $items[]=$r;
        }
        $res['items']=$items;

    return json_res(0,'ok',$res);
}


    function count_deliver_goods(){
        $id = Request::input('id');
        //$id = Request::input('id');
        //$user_list  = ShopUser::where('store_id',$id);
        
        // 刷新总物流提成
        $db_all=VOrder::where('status',4)->where('store_id',$id)->where('delivery_time','>',0);
        $all_wuliu_profit = round($db_all->sum('total_price') * 0.02,2);
        
        $db = SaleUser::find($id);
        $db->all_wuliu_profit = $all_wuliu_profit;
        $db->save();
        
        $res=array();
        $month_begin=date("Y-m-01 00:00:00");
        $db_month=VOrder::whereIn('status',[3,4])->where('store_id',$id)->where('delivery_time','>=',strtotime($month_begin));
        $res['month_sent_total']=$db_month->count();

        $rcs=$db_month->get()->toArray();
        $res['month_profit']=0;
        $rcs1 = VOrder::where('status',4)->where('store_id',$id)->where('delivery_time','>=',strtotime($month_begin))->get()->toArray();
        foreach ($rcs1 as $r){
            $res['month_profit']=$res['month_profit'] + $r['total_price']*0.02; 
        }
        $res['month_profit']=round($res['month_profit'],2);

        $res['wait_send_total']=VOrder::where('status',2)->where('store_id',$id)->count();
        return json_res(0,'ok',$res);
    }

  // 获得已发货订单
    function get_delivery_list(){
        $id = Request::input('id');
        $start_date = Request::input('start_date');
        $end_date = Request::input('end_date');
        $start = Request::input('start');
        $limit = Request::input('limit');
        $res=array();
        $db=VOrder::where('delivery_time','>=',strtotime($start_date))->where('store_id',$id)->whereIn('status',['3','4'])->where('delivery_time','<=',strtotime($end_date));
        $res['total_count']=$db->count();
        $res['total_price']=0;
        $res['total_profit']=0;

        $rcs=$db->get()->toArray();
        foreach ($rcs as $r){
            $res['total_price']=$res['total_price'] + $r['total_price']; 
            $res['total_profit']=$res['total_profit']+$r['total_price']*0.02; 
        }
        if($start !== NULL && $limit !== NULL){
          $db=$db->offset($start)->take($limit);
        }        
        $rcs=$db->get()->toArray();
        foreach ($rcs as $r){
            $r['created_at'] = date('Y-m-d H:i:s',$r['delivery_time']);
            $r['profit'] = round($r['total_price'] * 0.02,2);
            $res['items'][]=$r;
        }
        return json_res(0,'ok',$res);
    }
    
    function count_carriage_profit(){
        $id = Request::input('id');
        $start_date = Request::input('start_date');
        $end_date = Request::input('end_date');
        $start = Request::input('start');
        $limit = Request::input('limit');
        $res=array();
        $db=VOrder::where('delivery_time','>=',strtotime($start_date))->where('store_id',$id)->where('status','4')->where('delivery_time','<=',strtotime($end_date));
        $res['total_count']=$db->count();
        $res['total_price']=0;
        $res['total_profit']=0;

        $rcs=$db->get()->toArray();
        foreach ($rcs as $r){
            $res['total_price']=$res['total_price'] + $r['total_price']; 
            $res['total_profit']=$res['total_profit']+$r['total_price']*0.02; 
        }
        if($start !== NULL && $limit !== NULL){
          $db=$db->offset($start)->take($limit);
        }        
        $rcs=$db->get()->toArray();
        foreach ($rcs as $r){
            $r['created_at'] = date('Y-m-d H:i:s',$r['delivery_time']);
            $r['profit'] = round($r['total_price'] * 0.02,2);
            $res['items'][]=$r;
        }
        return json_res(0,'ok',$res);
    }

    function get_user_data(){
        $id = Request::input('id');
        $db = SaleUser::where('id',$id)->get()->first();
        unset($db['password']);
        return json_res(0,'ok',$db);
    }

    function update_password(){
        $uid=$this->get_user_id();
        if ($uid <=0) return json_res(1,'用户未登录');

        $old_pwd = Request::input('old_password');
        $new_pwd = Request::input('new_password');
        $db=SaleUser::find($uid);
        if (!$db) return json_res(1,'用户不存在');
        if ($db->password != $old_pwd) return json_res(1,'旧密码不正确');

        $db->password=$new_pwd;
        $db->save();
        return json_res(0,'ok');
    }

    function register_user(){
        $fds=array('mobile','verify_code','name','password','role_id','province','city','area');
        $req=Request::all();
        foreach($fds as $v)
        {
            if (!isset($req[$v])) return json_res(1,'缺少参数'.$v);
        }

        if ($req['role_id'] == 3 && !isset($req['store_linkman'])) return json_res(1,'缺少参数 store_linkman');

        $db=new SaleUser();
        $db->mobile=$req['mobile'];
        $db->name=$req['name'];
        $db->password=$req['password'];
        $db->role_id=$req['role_id'];
        $db->province=$req['province'];
        $db->city=$req['city'];
        $db->area=$req['area'];
        $db->store_linkman=$req['store_linkman'];
        $db->save();

        return json_res(0,'ok');
    }

    // 销售端H5 api 登录 post {mobile,password}
    function login(){
        $mobile = Request::input('mobile');
        $password = Request::input('password');
        $result = SaleUser::where('mobile',$mobile)->get()->first();
        if(!$result){
            return json_res(1,'用户名不存在');
        }
        $repassword = $result['password'];
        if($repassword != $password){
            return json_res(1,'密码错误');
        }
        //return var_dump($result);
        $token=random_string(16).$result['id'];
        $db=SaleUser::find($result['id']);
        $db->token=$token;
        $db->save();
        return response()->json(array('code'=>0, 'msg'=>'ok','data'=>[
                    'id'=>$result['id'],
                    'role_id'=>$result['role_id'],
                    'mobile'=>$result['mobile'],
                    'name'=>$result['name'],
                    'father_id'=>$result['father_id'],
                    'store_id'=>$result['store_id']
        ]))->withCookie("token",$token, 60*24*30)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    // 获取单个用户信息 
    function get_user_data_by_id($id){
        //用户信息数组
        $db=SaleUser::find($id)->toArray();
        unset($db['password']);

        $role_data=$this->get_role_data($db['role_id']);

        $db['profit_rate'] = $role_data['profit_rate'];
        $db['des'] = $role_data['des'];
        $db['role_key'] = $role_data['role_key'];
        return $db;
    }

    // 获取角色信息
    function get_role_data($role_id){
        $db = SaleRole::where('role_id',$role_id)->first()->toArray();
        return $db;
    }

    function get_user_id(){
//        return 2;

        $token= request()->cookie('token');
        if(!$token) return 0;
        $id=substr($token,16);
        return $id;
    }

    function get_user_data_by_cookie($rid=Null){
        $id=$this->get_user_id();
        $db=SaleUser::find($id);
        if(!$db) return 0;
        //if ($db->token != $token) return 0;
        if($rid !== Null){
            $res=$this->get_user_data_by_id($rid);
            return $res;
        }
        $res=$this->get_user_data_by_id($id);
        return $res;

        //        $res = $this->get_user_data_by_id(2);
    }

    // 搜索和分页
    function search_and_paging($db,$input_list,$start,$limit){
        // 根据条件搜索
        foreach($input_list as $k=>$v){
            if($v){
                $db->where($k,$v);
            }
        }       
        // 分页
        if ($start !== NULL && $limit !== NULL){
            if ($start <= 0) $start = 0;
            if ($limit > 20) $limit = 20;
            $db=$db->offset($start)->take($limit);
        }
        return $db;
    }


    // 获得下属用户的数组
    function get_my_user_list($id,$role_key){
        $res = array();
        $db = ShopUser::where($role_key,$id)->get()->toArray();
        foreach($db as $v){
            $res[] = $v['id'];
        }
        return $res;
    }

    /**--------------数据看板----------------------------**/
    //获得数据看板 route_path /get_order_data
    function get_data_statistics(){
        $id = Request::input('id');
        $res = $this->get_user_data_by_cookie($id);
        if(!$res){
            return json_res(1,'验证失败');
        }


        $role_key = $res['role_key'];
        $profit_rate = $res['profit_rate'];

        $date = array(
                'today'=>['start'=>date("Y-m-d 00:00:00"),'end'=>NULL],
                'yesterday'=>['start'=>date("Y-m-d 00:00:00",strtotime("-1 day")),'end'=>date('Y-m-d 00:00:00')],
                'month'=>['start'=>date("Y-m-01 00:00:00"),'end'=>NULL],
                'year'=>['start'=>date("Y-01-01 00:00:00"),'end'=>NULL],
                'all'=>['start'=>NULL,'end'=>NULL]
                );
        // 获取不同时间段用户数量
        $user_res = $this->get_user_count_by_date($id,$role_key,$date);      
        // 获取不同时间段销售额和利润
        $order_res = $this->get_order_and_price_count_by_date($id,$role_key,$date);      
        // 获取提成
        $profit_res = $this->get_profit_by_order_res($order_res,$profit_rate);     
        $result = array();
        foreach($date as $k=>$v){
            $result[$k]['user_count'] = $user_res[$k]['user_count'];
            $result[$k]['all_price'] = $order_res[$k]['all_price'];
            $result[$k]['order_count'] = $order_res[$k]['order_count'];
            $result[$k]['profit'] = $profit_res[$k]['profit'];
        }
        
        // 将总提成存入all_profit字段
        $db = SaleUser::find($id);
        $db->all_profit = $result['all']['profit'];
        $db->save();
        return json_res(0,'success',$result);
    }

    /***
     ** id(int):管理人员的id
     ** role_key(str):何种上级(ceo_id ? doctor_id ? store_id)
     ** date(arr):不同时间段的数组
     ** return(arr) 对应date数组的用户数量
     ***/
    function get_user_count_by_date($id,$role_key,$date){
        $res = array();
        foreach($date as $k=>$v){
            $result = $this->count_users($id,$role_key, $v['start'],$v['end']);
            $res[$k]['user_count'] = $result;
        }
        return $res;
    }
    /***
     **管理人员获得下属用户
     ** id(int):管理人员的id
     ** role_key(str):何种上级(ceo_id ? doctor_id ? store_id)
     ** start(date):用户创建时间的开始(包含)
     ** end(date):用户创建时间的结束(不包含)
     ** return 用户数量
     ***/
    function count_users($id,$role_key,$start,$end){    
        $db=ShopUser::where($role_key,$id); 
        if ($start != NULL) $db=$db->where('add_time','>',strtotime($start));
        if ($end != NULL) $db=$db->where('add_time','<=',strtotime($end));
        return $db->count();
    }

    //管理人员获得下属用户的订单
    function get_order_and_price_count_by_date($id,$role_key,$date){
        $res = array();
        $user_list = $this->get_my_user_list($id,$role_key);

        foreach($date as $k=>$v){
            $result = $this->get_order_and_price_count_by_user_list($user_list,$v['start'],$v['end']);
            $res[$k]['all_price'] = $result['all_price'];
            $res[$k]['order_count'] = $result['order_count'];
        }

        return $res;
    }

    // 根据用户列表获取订单数据
    function get_order_and_price_count_by_user_list($user_list,$start,$end){
        $res = array();

        if($start == NULL && $end == NULL){
            $db = Order::whereIn('user_id',$user_list)->where('status','4');        
        } else if($start == NULL){
          //
           // $db = Order::whereIn('user_id',$user_list)->where('status','4')->where('updated_at','<',strtotime($end));
           $db = Order::whereIn('user_id',$user_list)->where('status','4')->where('updated_at','<=',$end);
        } else if($end == NULL){
            //$db = Order::whereIn('user_id',$user_list)->where('status','4')->where('updated_at','>=',strtotime($start));
            $db = Order::whereIn('user_id',$user_list)->where('status','4')->where('updated_at','>',$start);
        } else {
          /*
            $db = Order::whereIn('user_id',$user_list)
                ->where('status','4')
                ->where('updated_at','>=',strtotime($start))
                ->where('updated_at','<',strtotime($end));
                */
                
          $db = Order::whereIn('user_id',$user_list)
                ->where('status','4')
                ->where('updated_at','>=',$start)
                ->where('updated_at','<',$end);
        }      
        if(!$db){
            return ['all_price'=>0,'order_count'=>0];
        }
        return ['all_price'=>($db->sum('price')),'order_count'=>($db->count())];
    }

    function get_profit_by_order_res($order_res,$profit_rate){
        $res = array();
        foreach($order_res as $k=>$v){
            $res[$k]['profit'] = round($v['all_price'] * $profit_rate,2);
        }
        return $res;
    }
    /**--------------------数据看板end----------------------------**/

    /**------------------------医生管理-----------------------------**/
    function search_doctor(){
        $name = Request::input('name');
        $mobile = Request::input('mobile');
        $myinfo = $this->get_user_data_by_cookie();
        if(!$myinfo){
            return json_res(1,'验证失败');
        }
        $id = $myinfo['id'];
        $role_key = $myinfo['role_key'];
        // 目前医生的role为2
        $doctor_role = SaleRole::where('des','医生')->get()->first()->role_id;

        //return $doctor_role;

        $search_list = ['name'=>$name,'mobile'=>$mobile];
        $res = $this->get_doctor_list_by_id($id,$role_key,$doctor_role,$search_list);

        return json_res(0,'ok',$res);
    }
    // 获取医生列表 id为管理者id
    function get_doctor_list_by_id($id,$role_key,$doctor_role,$search_list){        
        $db = SaleUser::where('role_id',$doctor_role)->where($role_key,$id);
        // 搜索
        foreach($search_list as $k=>$v){
            if($v){
                $db->where($k,'like','%'.$v.'%');
            }
        }
        return $db->get()->toArray();
    }
    /**------------------------医生管理end-----------------------------**/
    
    /**------------------------CEO管理-----------------------------**/
    function search_ceo(){
        $name = Request::input('name');
        $mobile = Request::input('mobile');
        $myinfo = $this->get_user_data_by_cookie();
        if(!$myinfo){
            return json_res(1,'验证失败');
        }
        $id = $myinfo['id'];
        $role_key = $myinfo['role_key'];
        // 目前医生的role为2
        $doctor_role = SaleRole::where('des','CEO')->get()->first()->role_id;

        //return $doctor_role;

        $search_list = ['name'=>$name,'mobile'=>$mobile];
        $res = $this->get_ceo_list_by_id($id,$role_key,$doctor_role,$search_list);

        return json_res(0,'ok',$res);
    }
    // 获取医生列表 id为管理者id
    function get_ceo_list_by_id($id,$role_key,$doctor_role,$search_list){        
        $db = SaleUser::where('role_id',$doctor_role)->where($role_key,$id);
        // 搜索
        foreach($search_list as $k=>$v){
            if($v){
                $db->where($k,'like','%'.$v.'%');
            }
        }
        return $db->get()->toArray();
    }
    /**------------------------医生管理end-----------------------------**/
    /**------------------------药店管理 获取列表-----------------------------**/
    function search_store_list(){
        $name = Request::input('name');
        $mobile = Request::input('mobile');
        $myinfo = $this->get_user_data_by_cookie();
        if(!$myinfo){
            return json_res(1,'验证失败');
        }
        $id = $myinfo['id'];
        $role_key = $myinfo['role_key'];
        // 目前药店的role为3
        $doctor_role = SaleRole::where('des','药店')->get()->first()->role_id;

        //return $doctor_role;

        $search_list = ['name'=>$name,'mobile'=>$mobile];
        $res = $this->get_store_list_by_id($id,$role_key,$doctor_role,$search_list);

        return json_res(0,'ok',$res);
    }
    // 获取医生列表 id为管理者id
    function get_store_list_by_id($id,$role_key,$doctor_role,$search_list){        
        $db = SaleUser::where('role_id',$doctor_role)->where($role_key,$id);
        // 搜索
        foreach($search_list as $k=>$v){
            if($v){
                $db->where($k,'like','%'.$v.'%');
            }
        }
        return $db->get()->toArray();
    }
    /**------------------------药店管理end-----------------------------**/
    /**------------------------药店管理start-----------------------------------**/
    // id为管理者id
    function search_store(){
        $myinfo = $this->get_user_data_by_cookie();
        if(!$myinfo){
            return json_res(1,'验证失败');
        }
        $id = $myinfo['id'];
        $role_key = $myinfo['role_key'];
        //return json_res(0,'ok',$role_key);
        // 获取药店的role_id
        $store_role = SaleRole::where('des','药店')->get()->first()->role_id;

        $db = SaleUser::where($role_key,$id)->where('role_id',$store_role)->get()->first();

        if(!$db){
            return json_res(1,'数据库获取失败');
        }
        $db = $db->toArray();
        $result = array(
                'id'=>$id,
                'name'=>$db['name'],
                'store_linkman'=>$db['store_linkman'],
                'address'=>$db['address']
                );
        return json_res(0,'ok',$result);
    }
    /**------------------------药店管理end-------------------------------------**/

    /**------------------------用户管理start--------------------------------------------**/
    function search_users(){
        $nickname = Request::input('username');
        $mobile = Request::input('mobile');
        $start_date = Request::input('start_date');
        $end_date = Request::input('end_date');
        $start = Request::input('start');
        $limit = Request::input('limit');

        $myinfo = $this->get_user_data_by_cookie();
        if(!$myinfo){
            return json_res(1,'验证失败');
        }
        $id = $myinfo['id'];
        $role_key = $myinfo['role_key'];

        $search_list = ['nickname'=>$nickname,'mobile'=>$mobile];

        $db = ShopUser::where($role_key,$id);

        if ($start_date) {$db->where('add_time','>=',strtotime($start_date));}
        if ($end_date) {$db->where('add_time','<',strtotime($end_date.' 23:59:59'));}
        // 搜索
        foreach($search_list as $k=>$v){
            if($v){
                $db->where($k,'like','%'.$v.'%');
            }
        }
        $total = $db->count();
        $db->orderBy('add_time','desc');
        // 分页
        if ($start !== NULL && $limit !== NULL){
            if ($start <= 0) $start = 0;
            if ($limit > 20) $limit = 20;
            $db=$db->offset($start)->take($limit);
        }

        $db = $db->get(['add_time','nickname','mobile','username']);

        foreach($db as $v){
            $v['created_at'] = date('Y-m-d H:i:s',$v['add_time']);
            $v['username'] = $v['nickname'];
            $v['test'] = strtotime($start_date);
            $v['test2'] = date('Y-m-d H:i:s',1645200000);
            unset($v['add_time']);
        }      
        return json_res(0,'ok',['total'=>$total,'items'=>$db]);
    }
    /**------------------------用户管理end--------------------------------------------**/

    /**------------------------订单管理start--------------------------------------------**/
    function search_orders(){

        $username = Request::input('username');
        $goods = Request::input('goods');
        $start_date = Request::input('start_date');
        $end_date = Request::input('end_date');
        $start = Request::input('start');
        $limit = Request::input('limit');

        $myinfo = $this->get_user_data_by_cookie();
        if(!$myinfo){
            return json_res(1,'验证失败');
        }
        $id = $myinfo['id'];
        $role_key = $myinfo['role_key'];

        $search_list = ['username'=>$username,'title'=>$goods];

        //获取用户列表
        $user_list = $this->get_user_list_by_id($id,$role_key);

        $order_list = $this->get_order_list_by_user_list($user_list,$search_list,$start_date,$end_date,$start,$limit);
        return json_res(0,'ok',$order_list);
    }

    function get_user_list_by_id($id,$role_key){
        $db = ShopUser::where($role_key,$id)->get('id')->toArray();
        $res = array();
        foreach($db as $v){
            $res[] = $v['id']; 
        }
        return $res;
    }
    function get_order_list_by_user_list($user_list,$search_list,$start_date,$end_date,$start,$limit){
        $db = ViewOrder::whereIn('user_id',$user_list);
        if($start_date){
            //$db->where('status','4')->where('updated_at','>=',strtotime($start_date));
            $db->where('status','4')->where('updated_at','>=',$start_date);
        }
        if($end_date){
            //$db->where('status','4')->where('updated_at','<',strtotime($end_date));
            $db->where('status','4')->where('updated_at','<',$end_date.' 23:59:59');
        }
        $db->where('status','4')->where('updated_at','>',0)->orderBy('updated_at','desc');
        // 搜索
        foreach($search_list as $k=>$v){
            if($v){
                $db->where($k,'like','%'.$v.'%');
            }
        }
        $total = $db->count();
        $total_price = $db->sum('total_price');
        // 分页
        if ($start !== NULL && $limit !== NULL){
            if ($start <= 0) $start = 0;
            if ($limit > 20) $limit = 20;
            $db=$db->offset($start)->take($limit);
        }

        $res=$db->get(['id','username','title','updated_at','total_price','buy_number_count','mobile'])->toArray();
        $data=array();
        
        foreach($res as $v){
            $v['pay_time'] = $v['updated_at'];
            $data[]=$v;
        }

        return ['total'=>$total,'total_price'=>$total_price,'items'=>$data];
    }
    /**------------------------订单管理end--------------------------------------------**/
    /**------------------------销售提成start--------------------------------------------**/
    function search_profits(){
        $start_date = Request::input('start_date');
        $end_date = Request::input('end_date');
        $res = $this->get_user_data_by_cookie();
        if(!$res){
            return json_res(1,'验证失败');
        }
        $id = $res['id'];
        $role_key = $res['role_key'];
        $profit_rate = $res['profit_rate'];

        // 获取下属医生，药店列表
        $db = SaleUser::whereIn('role_id',['2','3'])->where($role_key,$id);
        $user_list = $db->get('id')->toArray();
        foreach($user_list as $k=>$v){
            $user_list[$k] = $v['id']; 
        }
        $result = array();
        foreach($user_list as $v){
            $result[] = $this->get_data_statistics_for_profit($v,$start_date,$end_date);
        }
        return json_res(0,'ok',$result);
    }
    //数据面板改造
    function get_data_statistics_for_profit($id,$start_date,$end_date){
        $res = $this->get_user_data_by_id($id);

        $role_key = $res['role_key'];
        $profit_rate = $res['profit_rate']; 

        $date = array(
                'today'=>['start'=>date("Y-m-d 00:00:00"),'end'=>NULL],
                'yesterday'=>['start'=>date("Y-m-d 00:00:00",strtotime("-1 day")),'end'=>date('Y-m-d 00:00:00')],
                //'month'=>['start'=>date("Y-m-01 00:00:00"),'end'=>NULL],
                //'year'=>['start'=>date("Y-01-01 00:00:00"),'end'=>NULL],
                'all'=>['start'=>NULL,'end'=>NULL],
                'search_time'=>['start'=>$start_date,'end'=>$end_date]
                );
        // 获取不同时间段用户数量
        $user_res = $this->get_user_count_by_date($id,$role_key,$date);      
        // 获取不同时间段销售额和利润
        $order_res = $this->get_order_and_price_count_by_date($id,$role_key,$date);      
        // 获取提成
        $profit_res = $this->get_profit_by_order_res($order_res,$profit_rate);     
        $result = array();
        foreach($date as $k=>$v){
            $result[$k]['user_count'] = $user_res[$k]['user_count'];
            $result[$k]['all_price'] = $order_res[$k]['all_price'];
            $result[$k]['order_count'] = $order_res[$k]['order_count'];
            $result[$k]['profit'] = $profit_res[$k]['profit'];
        }
        return ['name'=>$res['name'],'role_id'=>$res['role_id'],'data'=>$result];
    }
    /**------------------------销售提成end--------------------------------------------**/
}

